﻿using AutoMapper;
using BW.MesProject.Public.ErrorCode;
using BW.MesProject.Public.Infrastructure;
using BW.MesProject.WareHouse.Domain;
using BW.MesProject.WareHouse.Infrastructure;
using BW.MesProject.WareHouse.Infrastructure.Dto.Input;
using BW.MesProject.WareHouse.Infrastructure.Dto.OutPut;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yitter.IdGenerator;

namespace BW.MesProject.WareHouse.Application
{
    /// <summary>
    /// 工序分类
    /// </summary>
    public class ProcessclassServices : IProcessclassServices
    {
        private readonly IBaseRepository<ProcessclassModel> _processclass;
        private readonly IBaseRepository<EMPModel> _Emp;
        private readonly IMapper _mapper;
        
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="processclass"></param>
        /// <param name="EmpModel"></param>
        /// <param name="mapper"></param>
        public ProcessclassServices(IBaseRepository<ProcessclassModel> processclass, IBaseRepository<EMPModel> EmpModel, IMapper mapper)
        {
            _processclass = processclass;
            _Emp = EmpModel;
            this._mapper = mapper;
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="processclass"></param>
        /// <returns></returns>
        public ApiResult<int> AddProcessClass(ProcessclassModel processclass)
        {
            try
            {
                //判断工艺分类编码，名称是否为空
                if (string.IsNullOrEmpty(processclass.PCId) || string.IsNullOrEmpty(processclass.PCName))
                {
                    return new ApiResult<int>()
                    {
                        Code = ApiEnums.Fail,
                        Message = "请检查工艺分类编码，名称是否为空"
                    };
                }
                var model = _processclass.GetValue(x => x.PCId == processclass.PCId);
                if (model != null && !string.IsNullOrEmpty(model.PCId))
                {
                    return new ApiResult<int>()
                    {
                        Code = ApiEnums.Fail,
                        Message = "工艺分类编号重复，请重新检查修改！！！"
                    };
                }
                model = _processclass.GetValue(x => x.PCName == processclass.PCName);
                if (model != null && !string.IsNullOrEmpty(model.PCName))
                {
                    return new ApiResult<int>()
                    {
                        Code = ApiEnums.Fail,
                        Message = "工艺分类名称重复，请重新检查修改！！！"
                    };
                }

                //添加
                var models = _mapper.Map<ProcessclassModel>(processclass);

                return new ApiResult<int>
                {
                    Code = ApiEnums.Success,
                    Message = "添加成功",
                    Data = _processclass.Add(processclass),
                    TotalCount = 0
                };
            }
            catch (Exception ex)
            {
                // 记录异常信息
                Console.WriteLine($"添加工艺分类时发生异常: {ex.Message}");

                return new ApiResult<int>()
                {
                    Code = ApiEnums.Fail,
                    Message = $"添加失败: {ex.Message}",
                    Data = 0,
                    TotalCount = 0
                };
            }
        }

      
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="qryInput"></param>
        /// <returns></returns>
        public ApiResult<List<ProcessclassOut>> GetProcessclass(QryInput qryInput)
        {
            try
            {
                int totalCount = 0;
                
                // 获取所有库位
                var list = _processclass.GetAll().Where(x => x.IsDeleted == false);
                

                if (qryInput.PageSize == 0)
                {

                    list = list.OrderBy(u => u.CreatedTime).Where(x => x.IsEnable == true);
                }
                else
                {

                    // 按编码查询
                    if (!string.IsNullOrEmpty(qryInput.QryID) && !string.IsNullOrEmpty(qryInput.QryName))
                    {
                        list = list.Where(x => x.PCId.Contains(qryInput.QryID) && x.PCName.Contains(qryInput.QryName));
                    }
                    else if (!string.IsNullOrEmpty(qryInput.QryID))
                    {
                        list = list.Where(x => x.PCId.Contains(qryInput.QryID));
                    }
                    else if (!string.IsNullOrEmpty(qryInput.QryName))
                    {
                        list = list.Where(x => x.PCName.Contains(qryInput.QryName));
                    }


                }
                // 处理结果数据
                var result = new List<ProcessclassOut>();

                //链表查询
                var query1 = list.LeftJoin<EMPModel>((a, b) => a.CreatedBy == b.EMPID).Select((a, b) =>
                    new ProcessclassOut
                    {
                        PCId = a.PCId,
                        PCName = a.PCName,
                        PCNum = a.PCNum,
                        Memo = a.Memo,//描述
                        EMPID = b.EMPID,
                        EMPName = b.EMPName,
                        CreatedBy = a.CreatedBy,
                        CreatedTime = a.CreatedTime,
                        UpdatedTime = a.UpdatedTime,
                        IsDeleted = a.IsDeleted,
                        IsEnable = a.IsEnable
                    });

                //获取集合
                var queryList = query1?.ToList();


                // 分页处理
                if (qryInput.PageSize > 0)
                {
                    queryList = queryList
                        .OrderBy(a => a.PCId).ThenBy(x => x.CreatedTime)
                        .Skip((qryInput.PageNum - 1) * qryInput.PageSize)
                        .Take(qryInput.PageSize)
                        .ToList();
                }

                return new ApiResult<List<ProcessclassOut>>()
                {
                    Code = ApiEnums.Success,
                    Message = "查询成功",
                    Data = queryList,
                    TotalCount = queryList.Count(),
                    PageNum = qryInput.PageNum,
                    PageSize = qryInput.PageSize
                };

            }
            catch (Exception ex)
            {
                // 记录异常信息
                Console.WriteLine($"查询工艺分类时发生异常: {ex.Message}");
                
                return new ApiResult<List<ProcessclassOut>>()
                {
                    Code = ApiEnums.Fail,
                    Message = $"查询失败: {ex.Message}",
                    Data = new List<ProcessclassOut>(),
                    TotalCount = 0
                };
            }
        }

       /// <summary>
       /// 修改
       /// </summary>
       /// <param name="model"></param>
       /// <returns></returns>
        public ApiResult<int> UpdateProcessclass(ProcessclassModel model)
        {
            try
            {
                //根据id查询是否有这条数据没有就修改不了
                var query = _processclass.GetValue(x => x.PCId == model.PCId);
                if (query == null)
                {
                    return new ApiResult<int>()
                    {
                        Code = ApiEnums.Fail,
                        Message = "修改失败，未找到指定的工艺分类信息",
                        Data = 0,
                        TotalCount = 0
                    };
                }

                //保存添加人和添加时间，添加修改人和修改时间
                _processclass.Update(model);
                
                return new ApiResult<int>()
                {
                    Code = ApiEnums.Success,
                    Message = "修改成功",
                    Data = 1,
                    TotalCount = 0
                };
            }
            catch (Exception ex)
            {
                // 记录异常信息
                Console.WriteLine($"修改工艺分类时发生异常: {ex.Message}");
                
                return new ApiResult<int>()
                {
                    Code = ApiEnums.Fail,
                    Message = $"修改失败: {ex.Message}",
                    Data = 0
                };
            }
        }

        /// <summary>
        /// 修改启用
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ApiResult<int> UpdateEnable(ProcessclassModel model)
        {
            var IsEnable=model.IsEnable;
            //根据id修改逻辑删除为 false
             model = _processclass.GetValue(x => x.PCId == model.PCId);
            model.IsEnable = IsEnable;
            var Message = string.Empty;
            if (IsEnable)
            {
                Message = "启用成功";
            }
            else
            {
                Message = "停用成功";
            }
            return new ApiResult<int>()
            {
                Code = ApiEnums.Success,
                Message = Message,
                Data = _processclass.Update(model),
                TotalCount = 0
            };

        }

        /// <summary>
        /// 软删除（修改状态）
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public ApiResult<int> UpdateDelete(string Id)
        {
            //根据id修改逻辑删除为 false
            var model = _processclass.GetValue(x => x.PCId == Id);
            model.IsDeleted = true;
            return new ApiResult<int>()
            {
                Code = ApiEnums.Success,
                Message = "删除成功",
                Data = _processclass.Update(model),
                TotalCount = 0
            };
        }

        /// <summary>
        /// 查询表是否有该编码
        /// </summary>
        /// <param name="PCId"></param>
        /// <returns></returns>
        public ApiResult<int> GetPCId(string PCId)
        {
            var model = _processclass.GetValue(x => x.PCId == PCId);
            return new ApiResult<int>()
            {
                Code = ApiEnums.Success,
                Message = "成功",
                Data = 1,
                TotalCount = 0
            };

        }
    }
}
